package bean

import (
	"fmt"
	"time"
	"user-agent/database"
	"user-agent/database/schema"

	"github.com/huyinghuan/moment"
)

type AliveBean struct{}

func (bean *AliveBean) GetOneAllActivity(mac string, limit int) ([]schema.Alive, error) {
	engine := database.GetDriver()
	list := []schema.Alive{}
	sql := `SELECT * from %s where mac = ? ORDER BY created desc limit 0, ? `
	sql = fmt.Sprintf(sql, "alive")
	err := engine.SQL(sql, mac, limit).Find(&list)
	return list, err
}

func (bean *AliveBean) GetRecordStatistics(mac string) (map[string]string, error) {
	sql := `
	select * from
	(select count(id) as count from alive where mac = ?)A,
    (SELECT created_date as end_date FROM alive WHERE id=(SELECT MAX(id) FROM alive where mac= ?)) B,
    (SELECT created_date as start_date FROM alive WHERE id=(SELECT MIN(id) FROM alive where mac= ?))C
	`
	result := map[string]string{}
	engine := database.GetDriver()
	_, err := engine.SQL(sql, mac, mac, mac).Get(&result)
	return result, err
}

//func (bean *AliveBean) GetAllCount(mac string) (int64, error) {
//	alive := new(schema.Alive)
//	engine := database.GetDriver()
//	return engine.Where("mac = ?", mac).Count(alive)
//}

func (bean *AliveBean) GetPeriodCount(mac string, start int64, end int64) (int64, error) {
	engine := database.GetDriver()
	alive := new(schema.Alive)
	sql := fmt.Sprintf(`SELECT count(*) from %s where mac = ? and created >= ? and created <= ?`, "alive")
	return engine.SQL(sql, mac, start, end).Count(alive)
}

func (bean *AliveBean) GetPeriodData(mac string) (map[string]string, error) {
	engine := database.GetDriver()
	now := moment.Now()
	weekago := now.LastDay(7).Unix()
	monthago := now.LastDay(30).Unix()
	sql := fmt.Sprintf(`
		SELECT * FROM 
			(SELECT %s AS forever FROM statistics where mac = ?)  allCount,
			(SELECT %s AS week FROM statistics where mac = ? and created_time > ?)  weekCount,
			(SELECT %s AS month FROM statistics where mac = ? and created_time > ?)  monthCount
	`, "`count`", "`count`", "`count`")
	p := map[string]string{}
	r, err := engine.Query(sql, mac, mac, weekago, mac, monthago)
	if err != nil {
		return nil, err
	}
	for k, v := range r[0] {
		p[k] = string(v)
	}
	return p, nil
}

func (bean *AliveBean) Insert(item *schema.Alive) error {
	engine := database.GetDriver()
	now := time.Now()
	item.Created = now.Unix()
	item.CreatedDate = now.Format("2006-01-02 15:04:05")
	_, err := engine.Insert(item)
	return err
}
